<?php
declare(strict_types=1);

namespace Zlf\Sms\Drive;

use Zlf\Sms\Drive\Config\Fxconfig;
use Zlf\Sms\SmsResult;
use Zlf\Request\Http;
use Zlf\Unit\Xml;

/**
 * 成都德昭分享科技有限公司
 * @link  http://cf.82009668.com
 */
class Fxsms extends SmsBasics
{

    /**
     * 发送短信接口
     */
    const SEND_SMS = '/SDK/Service.asmx/sendMessage';

    /**
     * 获取短信余额
     */
    const GET_BALANCE = '/SDK/Service.asmx/getBalance';


    /**
     * 获取短信余额
     * @return int
     */
    public function getBalance(): int
    {
        $conf = $this->getConfig();
        $api = $conf->host . self::GET_BALANCE;
        $post = Http::post($api, http_build_query([
            'username' => $conf->username,
            'password' => $conf->password,
        ]));
        if (isset($post['result']) && $post['result']) {
            $encode = mb_detect_encoding($post['result'], ["ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5']);
            $body = mb_convert_encoding($post['result'], 'UTF-8', $encode);
            $result = Xml::ToArray($body);
            return intval($result[0] ?? 0);
        }
        return 0;
    }


    /**
     * 发送短信
     * @param string $phone
     * @param string $template_key
     * @param array $data
     * @doc http://cf.82009668.com:888/SDK/Service.asmx?op=sendMessage 官方接口测试地址
     * @return SmsResult
     */
    public function send(string $phone, string $template_key, array $data = []): SmsResult
    {
        $conf = $this->getConfig();
        $content = $this->renderContent($conf->template, $template_key, array_merge($data, ['signature' => $conf->signature]));
        $data = [
            'username' => $conf->username,
            'pwd' => $conf->password,
            'phones' => $phone,
            'contents' => $content,
            'scode' => '',//参数可为空，但不能没有
            'setTime' => ''//参数可为空，但不能没有
        ];
        $api = $conf->host . self::SEND_SMS;
        $post = Http::post($api, http_build_query($data));
        $request = null;
        if (isset($post['result']) && $post['result']) {
            $encode = mb_detect_encoding($post['result'], ["ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5']);
            $request = mb_convert_encoding($post['result'], 'UTF-8', $encode);
            $result = Xml::ToArray($request);
            if (isset($result[0]) && ($result[0] === 1 || $result[0] === '1')) {
                return new SmsResult(['phone' => $phone, 'content' => $content, 'status' => true, 'driver' => static::class, 'template_key' => $template_key, 'request' => $request]);
            }
        }
        return new SmsResult(['phone' => $phone, 'content' => $content, 'status' => false, 'driver' => static::class, 'template_key' => $template_key, 'request' => $request]);
    }


    /**
     * 获取短信配置
     * @return Fxconfig
     */
    protected function getConfig(): Fxconfig
    {
        return parent::getConfig();
    }
}